/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component, Fragment} from 'react';
import {
  Form, Input, Radio, Select, Icon,
  DatePicker, TreeSelect, Divider, Modal, Table, Button, message,
} from 'antd';
import {connect} from 'dva';
import moment from 'moment'
import request from '@/utils/request';
import BuildModalTitle from "@/components/BuildModalTitle";
import {afterCloseModal, deleteTreeChildren} from "@/utils/utils";
import AddOrEditPrice from "@/pages/Departments/AddOrEditPrice";
import find from "lodash/find";
import department from "@/images/department.png";
const FormItem = Form.Item;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;
const { confirm } = Modal;
@connect(({ inner_address_book, loading, global }) => ({
  inner_address_book,
  global,
  loading: loading.models.inner_address_book,
}))
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));

    this.state = {
      data:[],
      editRecord:{}
    };
  }

  componentDidMount() {
    this.fetch()
  }
  fetch=()=>{
    const that = this;
    request(`/all_departments`, {
      method: 'GET',
      params:{
        order_direction:'desc'
      }
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }

    });
  }
  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    request(`/departments/${this.state.editRecord.id}`, {
      method: 'PUT',
      data:{
        ...formValues,
        parent_id:formValues.parent_id?formValues.parent_id.split('$')[0]:'',
      }
    }).then((response) => {
      if (response.status === 200) {
        message.success('修改部门成功');
        that.setState({
          editModal: false,
        });
        that.fetch();
        that.props.refleshDepartments()
      }

    });
  };
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    request(`/departments`, {
      method: 'POST',
      data:{
        ...formValues,
        parent_id:formValues.parent_id?formValues.parent_id.split('$')[0]:'',
      }
    }).then((response) => {
      if (response.status === 200) {
        message.success('添加部门成功');
        that.setState({
          addModal: false,
        });
        that.fetch();
        that.props.refleshDepartments()
      }

    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    request(`/departments/${id}`, {
      method: 'DELETE',
    }).then((response) => {
      if (response.status === 200) {
        message.success('删除部门成功');
        that.fetch();
        that.props.refleshDepartments()
      }

    });
  };
  render() {
    const that = this;
    const {data} = this.state;
    console.log('data', deleteTreeChildren(data));
    const columns = [
      { title: '部门名称', dataIndex: 'name', key: 'name',
        render: (val, record) =>{
          return <span style={{fontWeight:'bold'}}><img src={department} style={{width:'20px',height:'20px',marginRight:'10px'
            ,position:'relative',top:'-4px'}} alt=""/>{val}</span>
        }
      },
      { title: '备注', dataIndex: 'remark', key: 'remark', width: '40%' },
      {
        title: '操作',
        key: 'right',
        width: 200,
        classname: 'operate',
        render: (val, record) => <Fragment>
          {
            find(this.permissions, { name: 'department_operation' }) &&
            <Fragment>
              <Button
                type="primary"
                size="small"
                icon="edit"
                onClick={(e) => {
                  e.stopPropagation();
                  this.setState({
                    editRecord: record,
                    editModal: true,
                  });
                }
                }
              >编辑
              </Button>
              <Button
                type="danger"
                size="small"
                icon="delete"
                onClick={(e) => {
                  e.stopPropagation();
                  confirm({
                    title: `确定要删除"${record.name}"吗?`,
                    content: '请谨慎操作！',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    centered: true,
                    maskClosable: true,
                    onOk() {
                      that.handleDelete(record.id);
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }
                }
              >删除
              </Button>
            </Fragment>
          }

        </Fragment>,
      },
    ];
    return (
      <div>
        <Form layout="inline" className="search-form" style={{ marginBottom:'8px' }}>
          <FormItem>
            {
              find(this.permissions, { name: 'department_operation' }) &&
              <Button
                icon="plus"
                type="primary"
                onClick={
                  () => {
                    this.setState({
                      addModal: true,
                    });
                  }
                }
              >
                添加部门
              </Button>
            }
          </FormItem>

        </Form>
        <Table  className="custom-small-table meter-table vendor-meter"
                rowKey={record => record.id}
                size={'small'}
                bordered pagination={false} columns={columns}
                scroll={{ x: true, y: 600 }}
                dataSource={data}/>
        <Modal
          title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal"
                                  title={`添加部门`}/>}
          destroyOnClose
          visible={this.state.addModal}
          centered
          onOk={this.handleAdd}
          className="addModal"

          afterClose={() => {
            afterCloseModal(); // destroyOnClose需要
          }}
          onCancel={() => {
            this.setState({ addModal: false, editRecord: {} });
          }}

        >
          <AddOrEditPrice
            type={'add'}
            data={data}
            wrappedComponentRef={(inst) => this.AddForm = inst}
          />

        </Modal>
        <Modal
          title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                  title={`修改 ${this.state.editRecord.name}`}/>}
          destroyOnClose
          visible={this.state.editModal}
          centered
          onOk={this.handleEdit}
          className="editModal"
          afterClose={() => {
            afterCloseModal(); // destroyOnClose需要
          }}
          onCancel={() => {
            this.setState({ editModal: false, editRecord: {} });
          }}

        >
          <AddOrEditPrice
            type={'edit'}
            data={data}
            editRecord={this.state.editRecord}
            wrappedComponentRef={(inst) => this.EditForm = inst}
          />

        </Modal>
      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default AddPoliciesFormWrap;


